package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取营业数据---查询最近三十天的数据
        LocalDate date = LocalDate.now();
        LocalDate beginDate = date.minusDays(30);
        LocalDate endDate = date.minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));
        //2.通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模板文件生成一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取sheet页
            XSSFSheet sheet = excel.getSheet("sheet1");
            //填充时间和概览数据
            sheet.getRow(1).getCell(1).setCellValue("时间："+beginDate+"至"+endDate);
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            //填充详细数据
            for (int i = 0; i < 30; i++) {
                LocalDate day = beginDate.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(day, LocalTime.MIN), LocalDateTime.of(day, LocalTime.MAX));
                XSSFRow r = sheet.getRow(7 + i);
                r.getCell(1).setCellValue(day.toString());
                r.getCell(2).setCellValue(data.getTurnover());
                r.getCell(3).setCellValue(data.getValidOrderCount());
                r.getCell(4).setCellValue(data.getOrderCompletionRate());
                r.getCell(5).setCellValue(data.getUnitPrice());
                r.getCell(6).setCellValue(data.getNewUsers());
            }

            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //4.关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询营业额
     * @param start
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate start, LocalDate end) {

        //计算横坐标
        List<LocalDate> dateList = new ArrayList<>();
        while(!start.equals(end)) //这边要用equals不能用==
        {
            dateList.add(start);
            start = start.plusDays(1);
        }
        dateList.add(end);

        //查询纵坐标
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            Map map = new HashMap();
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.getTurnover(map);
            turnover = turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        }

        //封装返回值
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户数据统计
     * @param start
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate start, LocalDate end) {

        //计算横坐标
        List<LocalDate> dateList = new ArrayList<>();
        while(!start.equals(end)) //这边要用equals不能用==
        {
            dateList.add(start);
            start = start.plusDays(1);
        }
        dateList.add(end);

        //存放每天的新增用户数量select count(id) from user where create_time > ? and create_time < ?
        List<Integer> newUserList = new ArrayList<>();
        //存放每天的总用户数量select count(id) from user where create_time < ?
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            Map map = new HashMap();
            map.put("end",LocalDateTime.of(date,LocalTime.MAX));
            //总用户数量
            Integer totalUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
            //新增用户数量
            map.put("begin",LocalDateTime.of(date,LocalTime.MIN));
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);
        }
        //封装结果数据
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 订单数据统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //计算横坐标
        List<LocalDate> dateList = new ArrayList<>();
        while(!begin.equals(end)) //这边要用equals不能用==
        {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);

        //订单数列表
        List<Integer>orderCountList = new ArrayList<>();
        //有效订单数列表
        List<Integer>validOrderCountList = new ArrayList<>();
        //订单总数
        Integer totalOrderCount=0;
        //有效订单总数
        Integer validOrderCount=0;
        for (LocalDate date : dateList) {
            //select count(id) where status=? and create_time>? and create_time<?
            Map map = new HashMap();
            map.put("begin",LocalDateTime.of(date,LocalTime.MIN));
            map.put("end",LocalDateTime.of(date,LocalTime.MAX));
            Integer orderCount = orderMapper.getOrderCount(map);
            map.put("status",Orders.COMPLETED);
            Integer validOrder = orderMapper.getOrderCount(map);
            orderCountList.add(orderCount);
            totalOrderCount+=orderCount;
            validOrderCountList.add(validOrder);
            validOrderCount+=validOrder;
        }
        Double rate = 0.0;
        if(totalOrderCount!=0){
             rate = validOrderCount.doubleValue()/totalOrderCount.doubleValue();
        }

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .orderCompletionRate(rate)
                .build();
    }

    /**
     * 前十销量排名
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        List<GoodsSalesDTO> list = orderMapper.getOrdersTop10(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));
        //select od.name,od.sum(number) as number from order_detail od,orders o where od.order_id = o.id and o.status = 5 and o.order_time > ? and o.order_time < ? group by od.name order by number desc limit 0,10

        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }
}
